import Vue from 'vue'
import VueRouter from 'vue-router'
import {menuRouter} from "@/router/modules/system";
import store from '@/store/index'
// import {checkToken} from "@/api/system";
import {getJwtToken} from "@/lib/utils/TokenUtil";

Vue.use(VueRouter)
const Home = () => import('@/views/Home.vue')
// const Login = () => import('@/views/login/Login.vue')
const NotFount = () => import('@/exception/404')
const ForbiddenPage = () => import('@/exception/403')
const SystemErrorPage = () => import('@/exception/500')
const routes = [
  {
    path: '/',
    redirect:'/login'
  },
  {
    path: '/login',
    name: 'Login',
    meta:{title:'iMovie后台管理系统'},
    component: ()=>import('@/views/Login')
  },
  {
    path: '/index',
    name:'Home',
    component: Home,
    children:[
        ...menuRouter
    ]
  },
  {
    path:'/403',
    name:'403',
    component:ForbiddenPage
  },
  {
    path:'/500',
    name:'500',
    component:SystemErrorPage
  },
  {
    path:'*',
    name:'404',
    component:NotFount
  }
]

const router = new VueRouter({
  routes
})

// 全局路由后置守卫 当路由跳转后 做对应的添加tab操作
router.afterEach((to) => {
  if (to.path!=='/'&&to.path!==''&&to.path!=='/login'){
    console.log('afterEach');
    store.dispatch('addTab', to.path)
  }
})
router.beforeEach((to,from,next)=>{
  if (to.name === 'Login'){
    next()
  }else if (getJwtToken()!==''){
    next()
  }else {
    next('/login')
  }
})
// router.beforeEach((to,from,next)=>{
//   if (to.name === 'Login'){
//     next()
//   }else{
//     checkToken().then(()=>{
//       // console.log(res)
//       console.log("全局前置路由守卫beforeEach:checkToken方法:放行")
//       next()
//     }).catch(err=>{
//       console.log('全局前置路由守卫beforeEach:checkToken方法:errMsg:'+err);
//     })
//   }
// })

/*router.beforeEach((to,from,next)=>{
  if (to.name === 'Login'){
    next()
  }else{
    refreshToken().then(res=>{
      //如果token刷新成功
        // 将新获得的token保存起来
        setJwtToken(res.data)
        next()
    }).catch(err=>{
      console.log(err.message)
      setJwtToken('')
      next('/login')
    })
  }
})*/
export default router
